// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'

// 使用vue-material  ui 插件
import VueMaterial from 'vue-material'
import axios from 'axios'

// 使用moment.js 时间格式化 插件
import Moment from 'moment'

import 'vue-material/dist/vue-material.css'
import './assets/icon.css'
Vue.use(VueMaterial)
Moment.locale('en', {
  relativeTime: {
    future: '%s之后',
    past: '%s之前',
    s: '一秒',
    m: '一分钟',
    mm: '%d分',
    h: '一个小时',
    hh: '%d heures',
    d: '一天',
    dd: '%d天',
    M: '一个月',
    MM: '%d个月',
    y: '一年',
    yy: '%d年'
  }
})
Vue.filter('timerFilter', function(value) {
  return Moment(value).fromNow()
})

Vue.material.registerTheme({
  default: {
    primary: {
      color: 'light-green',
      hue: 700
    },
    accent: 'amber',
    warn: 'red',
    background: 'white'
  },
  indigo: {
    primary: 'indigo',
    accent: 'pink',
    warn: 'red',
    background: 'white'
  },
  teal: {
    primary: 'purple',
    accent: 'cyan',
    warn: 'red',
    background: 'white'
  },
  blue: {
    primary: 'blue',
    accent: 'deep-orange',
    warn: 'red',
    background: 'white'
  }
})

Vue.material.setCurrentTheme('default')


// http request 拦截器
axios.interceptors.request.use(
    config => {
            config.data = JSON.stringify(config.data)

        // if (localStorage.getItem('userToken')) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
        //     config.headers.Authorization = `token ` + localStorage.getItem('userToken')

        //     }
        // }
        return config;
    },
    err => {
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    localStorage.removeItem('userToken')
                    router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
                    })
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
    });

//  将axios挂载到prototype上 在组件中可以直接使用this.axios访问
Vue.prototype.axios = axios



/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  axios,
  template: '<App/>',
  components: { App }
})
